﻿using Qlab.Core.Entities;
using Qlab.SharedKernel.Interfaces;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;

namespace Qlab.Web.Api
{
    public class ToDoItemsController : BaseApiController
    {
        private readonly IRepository _repository;

        public ToDoItemsController(IRepository repository)
        {
            _repository = repository;
        }

        // GET: api/ToDoItems
        [HttpGet]
        public async Task<IActionResult> List()
        {
            var items = await _repository.QueryAsync<ToDoItem>();
            return Ok(items);
        }

        // GET: api/ToDoItems
        [HttpGet("{id:int}")]
        public async Task<IActionResult> GetById(int id)
        {
            var item = await _repository.GetByIdAsync<ToDoItem>(id);
            return Ok(item);
        }

        // POST: api/ToDoItems
        [HttpPost]
        public async Task<IActionResult> Post([FromBody] ToDoItem item)
        {
            await _repository.AddAsync(item);
            return Ok(item);
        }

        // POST: api/ToDoItems
        [HttpPut]
        public async Task<IActionResult> Update([FromBody] ToDoItem item)
        {
            await _repository.UpdateAsync(item);
            return Ok(item);
        }

        [HttpPatch("{id:int}/complete")]
        public async Task<IActionResult> Complete(int id)
        {
            var toDoItem = await _repository.GetByIdAsync<ToDoItem>(id);
            toDoItem.MarkComplete();
            await _repository.UpdateAsync(toDoItem);

            return Ok(toDoItem);
        }
    }
}